package starsservice.com.kc.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import common.common.Util.JWTutil;
import common.common.Util.UuidCreate;
import org.apache.commons.io.FileUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.multipart.MultipartFile;
import starsservice.com.kc.Util.JobNumber;
import starsservice.com.kc.Util.ResponseJson;
import starsservice.com.kc.bean.Account;
import org.springframework.stereotype.Service;
import starsservice.com.kc.config.UploadFileConfig;
import starsservice.com.kc.mapper.AccountMapper;
import starsservice.com.kc.service.IAccountService;
import starsservice.com.kc.service.IGroudService;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-12-13
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private IGroudService iGroudService;

    @Resource
    private UploadFileConfig uploadFileConfig;

    @Resource
    private ResponseJson responseJson;

    @Override
    public int InsterAccount(Account account) {
        account.setAccountId(UuidCreate.getUUID());
        account.setAccountJobNumber(JobNumber.jobNuber());
        account.setAccountAvatar("默认头像");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        account.setCreateTime(dateTimeFormatter.format(LocalDateTime.now()));
        account.setStats("1");//1为可用
        iGroudService.InsterGroud(account.getAccountId());
        return accountMapper.insert(account);
    }

    @Override
    public Account selectByphone(String phone) {
        return accountMapper.selectByphone(Wrappers.<Account>lambdaQuery().
                eq(Account::getAccountPhone, phone));
    }

    @Override
    public Account selectByjobnumber(String jobnumber) {
        return accountMapper.selectByphone(Wrappers.<Account>lambdaQuery().
                eq(Account::getAccountJobNumber, jobnumber));
    }


    /**
     * 文件上传操作，如果用户已经上传过5个头像那么降删除最早上传的一个。然后再保存最新的头像。
     *
     * @param file
     * @param token
     * @return
     */
    @Async
    @Override
    public void updateAvatar(MultipartFile file, String token) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder builder = new StringBuilder();
        String id = JWTutil.GetPayload(token, "visibleId");
        String fileType = file.getOriginalFilename().substring(Objects.requireNonNull(
                file.getOriginalFilename()).lastIndexOf("."));

        String fileName = builder.append(id).append("/").append(System.currentTimeMillis())
                .append(fileType).toString();
        builder.delete(0, builder.length());
//        id+"/"+System.currentTimeMillis() + fileType;
        String saveName = builder.append(uploadFileConfig.getUploadFolder()).append(fileName).toString();
        builder.delete(0, builder.length());

        /*以下是检测是否已经有5个头像如有那么进行删除最早的一个。*/

        File wilDelete = new File(builder.append(uploadFileConfig.getUploadFolder()).append(id).toString());
        builder.delete(0, builder.length());
        File[] tempList = wilDelete.listFiles();
        if (tempList != null) {
            List<Long> fileList = new ArrayList<>();

            if (tempList.length >= 5) {
                for (int i = 0; i < tempList.length; i++) {
                    long avatar = Long.valueOf(tempList[i].getName().substring(0, tempList[i].getName().indexOf(".")));
                    fileList.add(avatar);
                }
                OptionalLong optionalLong = fileList.stream().mapToLong(Long::longValue).min();
                String deleteName = builder.append(uploadFileConfig.getUploadFolder()).append(id).append("/")
                        .append(String.valueOf(optionalLong.getAsLong())).append(fileType).toString();
                wilDelete = new File(deleteName);
                wilDelete.delete();
            }
        }

        /*文件保存*/
        File update = new File(saveName);
        if (!update.getParentFile().exists()) {
            update.getParentFile().mkdirs();
        }

        try {
            /*改成异步方法此方法搁置。*/
//            file.transferTo(update);
            assert inputStream != null;
            FileUtils.copyInputStreamToFile(inputStream,update);
        } catch (IOException e) {
            log.error("文件上传失败,失败消息如下:"+e.getMessage());
            e.printStackTrace();
        }

        /*数据库保存头像的路径*/
        new LambdaUpdateChainWrapper<Account>(accountMapper)
                .eq(Account::getAccountId, id)
                .set(Account::getAccountAvatar, saveName).update();
    }
}
